package com.cuit.blog.controller;

import exception.UserAlreadyExistsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.cuit.blog.entity.Articletype;
import com.cuit.blog.entity.User;
import com.cuit.blog.service.ArticletypeService;
import com.cuit.blog.service.UserService;

import jakarta.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	UserService userService;
	int pageSize = 10;

	@PostMapping("/login")
	public String login(User user, HttpServletRequest request) {
		String username = user.getUsername();
		String pwd = user.getPwd();
		User loginUser = userService.login(username, pwd);
		System.out.println(">>>:" + username + ",>>>" + pwd);
		if (loginUser != null) {
			request.getSession().setAttribute("LoginUser", loginUser);
			return "redirect:/";
		}
		return "login";
	}

	@GetMapping("/findAll")
	public String findAll(Model model) {
		Page<User> page = userService.findAllByPage(0, pageSize);
		model.addAttribute("page", page);
		return "user/list";
	}

	@GetMapping("/page")
	public String findByPage(@RequestParam("pageIndex") int pageIndex, Model model) {
		Page<User> page = userService.findAllByPage(pageIndex, pageSize);
		int pre = page.previousOrFirstPageable().getPageNumber();
		int next = page.nextOrLastPageable().getPageNumber();
		model.addAttribute("pre", pre);
		model.addAttribute("next", next);
		model.addAttribute("page", page);
		return "user/list";
	}

	@PostMapping("/register")
	@ResponseBody
	public ResponseEntity<String> register(@RequestParam String username,
										   @RequestParam String pwd,
										   @RequestParam String email,
										   @RequestParam(required = false) String phone,
										   @RequestParam(required = false) String qq) {
		User user = new User();
		user.setUsername(username);
		user.setPwd(pwd);
		user.setEmail(email);
		user.setPhone(phone);
		user.setQq(qq);

		try {
			boolean isRegistered = userService.register(user);
			if (isRegistered) {
				return ResponseEntity.ok("注册成功！");
			} else {
				return ResponseEntity.badRequest().body("注册失败，请检查输入信息。");
			}
		} catch (IllegalArgumentException | UserAlreadyExistsException e) {
			return ResponseEntity.badRequest().body(e.getMessage());
		}
	}
}
